package com.wanfu.controller;

import com.wanfu.service.UserService;
import com.wanfu.util.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
public class LoginController {
    @Resource
    private UserService userService;

    @RequestMapping("/unauth")
    @ResponseBody
    public Object unauth () {
        return Result.error(Result.CODE_1100, "未登录");
    }

    @RequestMapping("/login")
    @ResponseBody
    public Object login (String userName, String password) throws Exception {
        UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
        Subject subject = SecurityUtils.getSubject();
        Result result;
        try {
            subject.login(token);
            result = Result.ok(subject.getSession().getId(), "ok");
        } catch (IncorrectCredentialsException e) {
            result = Result.error("密码错误");
        } catch (LockedAccountException e) {
            result = Result.error("登录失败，该用户已被冻结");
        } catch (AuthenticationException e) {
            result = Result.error("该用户不存在");
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.error();
        }
        return result;
    }
}
